package cn.zjj.basic.controller;

import cn.zjj.basic.util.FastDfsUtils;
import cn.zjj.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * @RequestPart : 接受文件统一用这个
     * @param file:名字和前端统一,elementui 默认文件名就是file
     *        required: true  必须填写 不然报错, false  不是必须填写
     * @return
     */
    @PostMapping//上传三要素之一,post
    public JsonResult upload(@RequestPart(value = "file",required = true) MultipartFile file){

        try {
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //从最后一个点开始截取       只需要后缀不需要.  所以要加1
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            //上传操作
            String path = FastDfsUtils.upload(file.getBytes(), substring);

            return new JsonResult().me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false,"上传失败");
        }
    }

    //删除文件的传值

    /**
     *
     * @param path
     * @RequestParam: 获取kv形式的值
     * @return
     */
    @DeleteMapping
    public JsonResult del(@RequestParam(value = "path",required = true) String path){
        try {
            String allpath = path.substring(1);//将第一个/去掉
            String groupPath = allpath.substring(0, allpath.indexOf('/'));//前闭后开,后面斜杠本来就不会算上
            String endPath = allpath.substring(allpath.indexOf('/')+1);//+1 斜杠后面开始算
            FastDfsUtils.delete(groupPath,endPath);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false,"删除失败");
        }
    }
}
